
#include "util.h"
#include <thread>
#include <sys/syscall.h>
#include <unistd.h>

#include <cstdio>
#include <cstdlib>

void ErrorIf(bool condition, const char *errmsg) {
  if (condition) {
    perror(errmsg);
    exit(EXIT_FAILURE);
  }
}

uint32_t GetThreadId() {
#ifdef OS_LINUX
    // linux平台的代码
    return (uint32_t)syscall(SYS_gettid);
#endif

#ifdef OS_MACOS
    // macos平台的代码
    std::__thread_id id = std::this_thread::get_id();
    return std::hash<std::thread::id>()(id);
#endif
}

std::string GetThreadName() {
    char thread_name[16] = {0};
    pthread_getname_np(pthread_self(), thread_name, 16);
    return std::string(thread_name);
}

void SetThreadName(const std::string &name) {
#ifdef OS_LINUX
    // linux平台的代码
    pthread_setname_np(pthread_self(), name.substr(0, 15).c_str());
#endif

#ifdef OS_MACOS
    // macos平台的代码
    pthread_setname_np(name.substr(0, 15).c_str());
#endif
}

uint64_t GetElapsedMS() {
    struct timespec ts = {0};
    clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
    return ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
}

